#include "db_connection.h"
#include "connection.h"
#include "service.h"
#include "db_connection_handler.h"
static int getIntFromBuffer( unsigned char* input, int inputLen )
{
	int ret = 0;
	for(int i = 0; i < inputLen; i++) {
		ret += ret * 256 + input[i];
	}
	return ret;
}

static void intToBuf( int data, unsigned char* buf )
{
	buf[0] = (data >> 24) & 0xff;
	buf[1] = (data >> 16) & 0xff;
	buf[2] = (data >> 8) & 0xff;
	buf[3] = data & 0xff;
}



DBConnection::DBConnection( Service* service, const std::string& host, int port )
{
	m_handler = NULL;
	m_service = service;
	m_host = host;
	m_port = port;
	m_conn = new Connection(service);
	m_conn->setHandler(this);
	m_conn->connect(host, port);
}

DBConnection::~DBConnection(void)
{
	if(m_conn) {
		m_conn->close();
	}
}

void DBConnection::onData( Connection* conn )
{
	int lenInput = conn->getBufferLen();
	if(lenInput < 4) {
		return;
	}

	unsigned char* lenBuf = (unsigned char*)conn->getBuffer(4);
	int lenData = getIntFromBuffer(lenBuf, 4);

	if(lenInput < lenData + 4) {
		return;
	}

	char* bufData = (char*)conn->getBuffer(lenData + 4) + 4;

	if(m_handler) {
		m_handler->onDBConnectionData(bufData, lenData);
	}
	conn->removeBuffer(lenData + 4);
}

void DBConnection::setHandler( DBConnectionHandler* handler )
{
	m_handler = handler;
}

void DBConnection::sendData( void* data, int len )
{
	unsigned char lenBuf[4] ={};
	intToBuf(len, lenBuf);
	m_conn->sendData((char*)lenBuf, 4);
	m_conn->sendData((char*)data, len);
}

void DBConnection::onClose( Connection* conn )
{
	m_conn = NULL;
}

void DBConnection::onConnected( Connection* conn )
{

}
